package com.webserver.core;

import com.sun.security.ntlm.Client;
import com.webserver.http.HttpServletRequest;

import java.io.*;
import java.net.Socket;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class ClientHandler implements Runnable{
    private Socket socket;
    public ClientHandler(Socket socket){
        this.socket=socket;
    }

    public void run() {

        try {
            HttpServletRequest request = new HttpServletRequest(socket);

            String path=request.getUri();

            File rootDir=new File(
                    ClientHandler.class.getClassLoader()
                    .getResource(".").toURI()
            );

            File staticDir= new File(rootDir,"static");

            File file=new File(staticDir,path);
            System.out.println("资源是否存在:"+file.exists());


            println("HTTP/1.1 200 OK");

            println("Content-Type:text/html");

            println("Content-Length:"+file.length());

            println("");

            FileInputStream fis=new FileInputStream(file);
            OutputStream out = socket.getOutputStream();
            byte[]buf=new byte[1024*10];
            int len;
            while((len=fis.read(buf))!=-1){
                out.write(buf,0,len);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    private void println(String line) throws IOException {
        OutputStream out=socket.getOutputStream();
        byte[]data = line.getBytes(StandardCharsets.ISO_8859_1);

        out.write(data);
       out.write(13);
       out.write(10);
    }

}
